package cn.dinkevin.xui.net;

import android.support.annotation.NonNull;

import com.google.gson.JsonParseException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import cn.dinkevin.xui.ErrorInfo;
import cn.dinkevin.xui.net.exception.ApiException;
import cn.dinkevin.xui.net.exception.BizException;
import cn.dinkevin.xui.util.LogUtil;
import io.reactivex.functions.Consumer;
import retrofit2.HttpException;

/**
 * Create with Android Studio
 * Author: chengpengfei
 * Date: 2018/5/6
 * Time: 10:17 AM
 * Description:自定义异常拦截处理
 */
public abstract class CustomErrorHandler<T extends Throwable> implements Consumer<T> {


    /**
     * 平台口令失效监控
     */
    public interface ITokenMonitor {

        void onTokenInvalid();
    }
    private static ITokenMonitor mAccessTokenMonitor;


    /**
     * 绑定全局统一的平台口令失效监控
     * @param monitor
     */
    public static void setTokenMonitor(ITokenMonitor monitor){
        mAccessTokenMonitor = monitor;
    }


    @Override
    public final void accept(@NonNull T e) throws Exception {

        if(e instanceof BizException){

            BizException bizExp = (BizException)e;
            LogUtil.format_e("BizException: %s",bizExp);

            switch (bizExp.getCode()){
                case ErrorInfo.INVALID_TOKEN:
                    onError(new ApiException(bizExp));
                    if(null != mAccessTokenMonitor){
                        mAccessTokenMonitor.onTokenInvalid();
                    }
                    return;
            }
        }
        else if(e instanceof HttpException){
            LogUtil.format_e("HttpException: %d %s",((HttpException) e).code(),((HttpException) e).response());
            onError(new ApiException(((HttpException) e).code(),((HttpException) e).message()));
        }
        else if(e instanceof ConnectException){
            LogUtil.format_e("ConnectException: %s",e);
            onError(new ApiException(ErrorInfo.CONNECT_ERROR));
        }
        else if(e instanceof UnknownHostException){
            LogUtil.format_e("UnknownHostException: %s",e);
            onError(new ApiException(ErrorInfo.UNKNOWN_HOST));
        }
        else if(e instanceof SocketTimeoutException){
            LogUtil.format_e("SocketTimeoutException: %s",e);
            onError(new ApiException(ErrorInfo.CONNECT_TIMEOUT));
        }else if(e instanceof JsonParseException){
            LogUtil.format_e("JsonParseException: %s",e);
            onError(new ApiException(ErrorInfo.JSON_PARSE_ERROR));
        }else{
            LogUtil.format_e("UnknownException: %s",e);
            onError(new ApiException(ErrorInfo.UNKNOWN));
        }
    }


    public abstract void onError(ApiException e);
}
